<template>
  <div class="scheduleTemplate">
    <!-- <div class="prewive">
      <span>{{$t('statement.tpwre')}}</span>
      <span class="numRecord">{{dataForm[scriptItem.text][scriptItem.number]}}</span>
      <span>{{ timeType }}&nbsp;</span>
      <span>{{$t('statement.sf')}}</span>
      <span class="dateRecord">{{formatDate(totalDetas) }}</span>
    </div> -->
    <div style="display:flex;border: 1px solid #F0F0F0;margin-top:10px">
      <div style="width:46px">
        <typeCustomRadio @selectRadio="selectRadio" :isSelect.sync="selectOption[0]"></typeCustomRadio>
      </div>
      <div style="width:100%">
        <div style="margin: 10px 0;display:flex;width:100%">
          <div style="width:100px;line-height:32px">{{$t('attribute.startingat')}}</div>
          <div style="width:100%;display:flex;align-items:center">
            <el-date-picker style="width: 40%;margin-left:10px"
                            v-model="dates"
                            :clearable="false"
                            format="MM/dd/yy"
                            @change="timePicker"
                            :default-value="new Date()"
                            type="date">
            </el-date-picker>
            <el-time-picker v-model="times"
                            :clearable="false"
                            style="width: 8rem;margin-left:10px"
                            @change="timePicker"
                            format="HH:mm:ss"
                            :default-value="new Date()">
            </el-time-picker>
            <!-- <span style="margin-left:10px;flex:1;" class="truncate">{{$store.state.user.timezoneId}}</span> -->
          </div>
        </div>
        <div style="margin:10px 0;display:flex">
          <div :span="4" style="line-height:32px">{{$t('statement.re')}}</div>
          <div :span="20">
            <el-input-number size="small"
                             :min="limit.min"
                             :max="limit.max"
                             style="left: 0;width: 31.5%;margin-left:10px"
                             v-model="dataForm[scriptItem.text][scriptItem.number]"
                             @change="numberChange"
                             :step='1'
                             step-strictly
                             controls-position="right"></el-input-number>
            <el-select style="width: 8rem;margin-left: 15px" @change="changeHanderler"
                       v-model="dataForm[scriptItem.text][scriptItem.dateValue]">
              <el-option v-for="item in options"
                         :key="item.label"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <div style="display:flex;border: 1px solid #F0F0F0;border-top:0">
      <div style="width:46px">
        <typeCustomRadio @selectRadio="selectRadio" :isSelect.sync="selectOption[1]"></typeCustomRadio>
      </div>
      <div>
        <div style="margin:10px 0;display:flex">
          <div :span="4" style="line-height:32px">{{$t('statement.re')}}</div>
          <div :span="20">
            <el-input-number size="small"
                             :min="1"
                             :max="59"
                             @change="changeHander"
                             style="left: 0;width: 31.5%;margin-left:10px"
                             v-model="dataForm[scriptItem.text][scriptItem.numberTwo]"
                             :step='1'
                             step-strictly
                             controls-position="right"></el-input-number>
            <span style="margin-left:10px">{{model==='snapshot' ? 'Hours':$t('statement.minutes')}} </span>
          </div>
        </div>
        <div style="margin:10px 0;display:flex">
          <div :span="4" style="line-height:32px">{{$t('statement.fh')}}</div>
          <div :span="4">
            <el-time-select
            @change="changeHand"
              style="width:100px;margin-left:10px" popper-class="custom_time_picker"
              v-model="dataForm[scriptItem.text][scriptItem.fromTwo]"
              :picker-options="{
                start: '00:00',
                step: '01:00',
                end: '23:00',
                maxTime: dataForm[scriptItem.text][scriptItem.toTwo]
              }">
            </el-time-select>
            <span style="margin-left:10px">to</span>
          </div>
          <div :span="4">
            <el-time-select
            @change="changeHand"
              style="width:100px;margin-left:10px" popper-class="custom_time_picker"
              v-model="dataForm[scriptItem.text][scriptItem.toTwo]"
              :picker-options="{
                start: '00:00',
                step: '01:00',
                end: '23:00',
                minTime: dataForm[scriptItem.text][scriptItem.fromTwo]
              }">
            </el-time-select>
            <span style="margin-left:10px">on day of week</span>
          </div>
          <div :span="4">
            <el-select style="width: 200px;margin-left: 15px"  multiple  collapse-tags clearable
                       v-model="dataForm[scriptItem.text][scriptItem.weekTwo]">
              <el-option v-for="item in optionsWeek"
                         :key="item.label"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <div style="display:flex;border: 1px solid #F0F0F0;border-top:0">
      <div style="width:46px">
        <typeCustomRadio @selectRadio="selectRadio" :isSelect.sync="selectOption[2]"></typeCustomRadio>
      </div>
      <div style="margin:10px 0;width:100%">
        <span style="line-height:32px">{{$t('statement.adsd')}}</span>
        <span style="margin-left:20px">{{this.dataForm[this.scriptItem.text][this.scriptItem.cronData]&&this.dataForm[this.scriptItem.text][this.scriptItem.cronData].cron}}</span>
        <el-popover width="700" v-model="refreshCronPopover" popper-class="cron_popover" @show="showData">
          <div style="display:flex;justify-content:space-between;margin-bottom:10px">
            <div style="font-weight:700">{{$t('statement.adsd')}}</div>
            <i class="el-icon-close icon_close" style="font-size:16px" @click="refreshCronPopover=false"></i>
          </div>
          <vue-cron @change="changeRefreshCron" :cronData="this.dataForm[this.scriptItem.text][this.scriptItem.cronData]"
                    ref="vuecron"
                    :model="model"
                    :shareDashboard="shareDashboard"
                    @close="refreshCronPopover=false"
                    i18n="en"></vue-cron>
          <span slot="reference" style="float:right" class="setting">{{$t('statement.setting')}}<i class="el-icon-right icon_right"></i></span>
        </el-popover>
      </div>
    </div>
  </div>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import moment from 'moment'
import typeCustomRadio from './type-custom-radio.vue'
import { TimeZoneNameList } from '@/utils'
export default {
  mixins: [mixinTypeViewModule],
  components: { typeCustomRadio },
  props: ['model', 'shareDashboard'],
  data () {
    return {
      options: this.model === 'snapshot' ? [
        // { label: 'Year', value: 'year' },
        { label: 'Month', value: 'month' },
        { label: 'Week', value: 'week' },
        { label: 'Day', value: 'day' },
        { label: 'Hour', value: 'hour' }
        // { label: 'Second', value: 'second' }
      ] : [
        // { label: 'Year', value: 'year' },
        { label: 'Month', value: 'month' },
        { label: 'Week', value: 'week' },
        { label: 'Day', value: 'day' },
        { label: 'Hour', value: 'hour' },
        { label: 'Minute', value: 'minute' }
        // { label: 'Second', value: 'second' }
      ],
      optionsWeek: [
        { label: 'Sunday', value: 'SUN' },
        { label: 'Monday', value: 'MON' },
        { label: 'Tuesday', value: 'TUE' },
        { label: 'Wednesday', value: 'WED' },
        { label: 'Thursday', value: 'THU' },
        { label: 'Friday', value: 'FRI' },
        { label: 'Saturday', value: 'SAT' }
      ],
      dates: null,
      times: null,
      totalDetas: null,
      selectOption: [true, false, false],
      value1: 1,
      refreshCronPopover: false,
      str: '3/5 0 * * * ? *',
      scheduleTimeZoneId: null,
      timezoneList: []
    }
  },
  watch: {
    selectOption: {
      handler (val) {
        if (val[2]) {
          if (this.dataForm[this.scriptItem.text][this.scriptItem.cronData]) {
            this.dataForm[this.scriptItem.text][this.scriptItem.cornstr] = this.dataForm[this.scriptItem.text][this.scriptItem.cronData].cron
          }
        }
        this.dataForm[this.scriptItem.text][this.scriptItem.selectId] = val.findIndex(i => i)
        if (this.dataForm[this.scriptItem.text][this.scriptItem.selectId] === 0) {
          this.dataForm[this.scriptItem.text][this.scriptItem.scheduleType] = 'CRON'
        } else if (this.dataForm[this.scriptItem.text][this.scriptItem.selectId] > 0) {
          this.dataForm[this.scriptItem.text][this.scriptItem.scheduleType] = 'CRON'
        } else {
          this.selectOption[0] = true
          this.dataForm[this.scriptItem.text][this.scriptItem.selectId] = 0
          this.dataForm[this.scriptItem.text][this.scriptItem.scheduleType] = 'CRON'
        }
      },
      deep: true
    },
    // dataForm: {
    //   handler: function (val) {
    //     if (val[this.scriptItem.text] && val[this.scriptItem.text][this.scriptItem.times] === '') {
    //       val[this.scriptItem.text][this.scriptItem.times] = new Date()
    //     }
    //   },
    //   immediate: true,
    //   deep: true
    // }
  },
  created () {
    this.initDate()
    this.numberChange(this.dataForm[this.scriptItem.text][this.scriptItem.number])
    this.dateValueChange(this.dataForm[this.scriptItem.text][this.scriptItem.dateValue])
    if (!this.dataForm[this.scriptItem.text][this.scriptItem.numberTwo]) {
      this.dataForm[this.scriptItem.text][this.scriptItem.numberTwo] = 1
    }
  },
  mounted () {
    this.numberChange(1)
  },
  computed: {
    timeType () {
      try {
        return this.options.find(e => e.value === this.dataForm[this.scriptItem.text][this.scriptItem.dateValue]).label
      } catch (error) {
        return ''
      }
    },
    limit () {
      let temp = {}
      switch (this.dataForm[this.scriptItem.text][this.scriptItem.dateValue]) {
        case 'month':
          temp = {
            min: 1,
            max: 12
          }
          break
        case 'week':
          temp = {
            min: 1,
            max: 1
          }
          break
        case 'day':
          temp = {
            min: 1,
            max: 31
          }
          break
        case 'hour':
          temp = {
            min: 1,
            max: 23
          }
          break
        case 'minute':
          temp = {
            min: 1,
            max: 59
          }
          break
        default:
          temp = {
            min: null,
            max: null
          }
          break
      }
      return temp
    }
  },
  methods: {
    changeTimeZone (val){
      this.$set(this.dataForm.scheduleTemplate, 'timezoneid', val)
      this.$set(this.dataForm.scheduleTemplate, 'timezoneoffset', moment.tz(val).format('Z'))
    },
    changeHand () {
      this.$forceUpdate()
    },
    reset () {
      Object.assign(this.$data, this.$options.data())
      if (this.model === 'snapshot') {
        this.options = [
        // { label: 'Year', value: 'year' },
          { label: 'Month', value: 'month' },
          { label: 'Week', value: 'week' },
          { label: 'Day', value: 'day' },
          { label: 'Hour', value: 'hour' }
        // { label: 'Second', value: 'second' }
        ]
      }
    },
    changeHanderler () {
      this.dataForm[this.scriptItem.text][this.scriptItem.number] = 1
    },
    changeHander () {
      this.$forceUpdate()
    },
    showData () {
      this.refreshCronPopover = true
      this.$nextTick(() => {
        this.$refs.vuecron.init()
        this.$forceUpdate()
      })
    },
    changeRefreshCron (val) {
      this.dataForm[this.scriptItem.text][this.scriptItem.cornstr] = val.cron
      this.dataForm[this.scriptItem.text][this.scriptItem.cronData] = val
    },
    selectRadio (selectId) {
      this.selectOption = [false, false, false]
    },
    initDate () {
      this.selectOption = [false, false, false]
      let index = this.dataForm[this.scriptItem.text][this.scriptItem.selectId]
      this.selectOption[index] = true
      // if (this.dataForm[this.scriptItem.text][this.scriptItem.times]) {
      //   this.totalDetas = this.dataForm[this.scriptItem.text][this.scriptItem.times]
      //   this.dates = moment(this.totalDetas.slice(0,-1)).format('YYYY-MM-DDTHH:mm:ss')
      //   this.times = moment(this.totalDetas.slice(0,-1)).format('YYYY-MM-DDTHH:mm:ss')
      // } else {
      //   this.times = new Date()
      //   this.dates = this.times
      //   let dates = this.times.getFullYear() + '-' + ((this.times.getMonth() + 1) > 9 ? (this.times.getMonth() + 1) : `0${(this.times.getMonth() + 1)}`) + '-' + (this.times.getDate() > 9 ? this.times.getDate() : `0${this.times.getDate()}`)
      //   let daTime = (this.times.getHours() > 9 ? this.times.getHours() : `0${this.times.getHours()}`) + ':' + (this.times.getMinutes() > 9 ? this.times.getMinutes() : `0${this.times.getMinutes()}`) + ':' + (this.times.getSeconds() > 9 ? this.times.getSeconds() : `0${this.times.getSeconds()}`)
      //   this.totalDetas = dates + 'T' + daTime + 'Z'
      //   // this.dataForm[this.scriptItem.text][this.scriptItem.times] = moment(this.totalDetas).utc().format()
      //   this.dataForm[this.scriptItem.text][this.scriptItem.times] = this.totalDetas
      // }
      if (this.dataForm[this.scriptItem.text][this.scriptItem.times]) {
        this.totalDetas = this.dataForm[this.scriptItem.text][this.scriptItem.times]
        this.dates = moment(this.totalDetas.slice(0,-1)).format('YYYY-MM-DDTHH:mm:ss')
        this.times = moment(this.totalDetas.slice(0,-1)).format('YYYY-MM-DDTHH:mm:ss')
      } else {
        this.times = new Date()
        this.dates = this.times
        let dates = this.times.getFullYear() + '-' + ((this.times.getMonth() + 1) > 9 ? (this.times.getMonth() + 1) : `0${(this.times.getMonth() + 1)}`) + '-' + (this.times.getDate() > 9 ? this.times.getDate() : `0${this.times.getDate()}`)
        let daTime = (this.times.getHours() > 9 ? this.times.getHours() : `0${this.times.getHours()}`) + ':' + (this.times.getMinutes() > 9 ? this.times.getMinutes() : `0${this.times.getMinutes()}`) + ':' + (this.times.getSeconds() > 9 ? this.times.getSeconds() : `0${this.times.getSeconds()}`)
        this.totalDetas = dates + 'T' + daTime + 'Z'
        // this.dataForm[this.scriptItem.text][this.scriptItem.times] = moment(this.totalDetas).utc().format()
        this.dataForm[this.scriptItem.text][this.scriptItem.times] = this.totalDetas
      }
      if(!this.dataForm[this.scriptItem.text].timezoneid){
        this.dataForm[this.scriptItem.text].timezoneid = this.$store.state.user.timezoneId
        this.dataForm[this.scriptItem.text].timezoneoffset = moment.tz(this.$store.state.user.timezoneId).format('Z')
      }
    },
    dataPicker (date) {
      let d = new Date(date)
      let t = new Date(this.times)
      let dates = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
      let daTime = t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds() + ':' + t.getMilliseconds()
      this.totalDetas = dates + '  ' + daTime
      this.dataForm[this.scriptItem.text][this.scriptItem.times] = moment(this.totalDetas).utc().format()
    },
    timePicker (time) {
      // let t = new Date(time)
      // let d = new Date(this.dates)
      // let dates = d.getFullYear() + '-' + ((d.getMonth() + 1) > 9 ? (d.getMonth() + 1) : `0${(d.getMonth() + 1)}`) + '-' + (d.getDate() > 9 ? d.getDate() : `0${d.getDate()}`)
      // let daTime = (t.getHours() > 9 ? t.getHours() : `0${t.getHours()}`) + ':' + (t.getMinutes() > 9 ? t.getMinutes() : `0${t.getMinutes()}`) + ':' + (t.getSeconds() > 9 ? t.getSeconds() : `0${t.getSeconds()}`)
      // this.totalDetas = dates + 'T' + daTime + 'Z'
      // // this.totalDetas = '2022-04-18T20:38:56'
      // // this.dataForm[this.scriptItem.text][this.scriptItem.times] = moment.tz(this.totalDetas, this.$store.state.user.timezoneId).utc().format()
      // this.dataForm[this.scriptItem.text][this.scriptItem.times] = this.totalDetas
      let t = new Date(time)
      let d = new Date(this.dates)
      let dates = d.getFullYear() + '-' + ((d.getMonth() + 1) > 9 ? (d.getMonth() + 1) : `0${(d.getMonth() + 1)}`) + '-' + (d.getDate() > 9 ? d.getDate() : `0${d.getDate()}`)
      let daTime = (t.getHours() > 9 ? t.getHours() : `0${t.getHours()}`) + ':' + (t.getMinutes() > 9 ? t.getMinutes() : `0${t.getMinutes()}`) + ':' + (t.getSeconds() > 9 ? t.getSeconds() : `0${t.getSeconds()}`)
      this.totalDetas = dates + 'T' + daTime + 'Z'
      this.dataForm[this.scriptItem.text][this.scriptItem.times] = this.totalDetas
    },
    numberChange (e) {
      if (!e) {
        this.$nextTick(() => {
          this.dataForm[this.scriptItem.text][this.scriptItem.number] = 1
        })
      }
      // this.dataForm[this.scriptItem.text][this.scriptItem.cornstr] = this.getTimeSecond()
    },
    dateValueChange (e) {
      this.$nextTick(() => {
        // this.dataForm[this.scriptItem.text][this.scriptItem.cornstr] = this.getTimeSecond()
      })
    },
    // setScheduleType () {
    // this.$set(this.dataForm[this.scriptItem.text], 'scheduleType', 'FIX_RATE')
    // },
    getTimeSecond () {
      // this.setScheduleType()
      let second
      switch (this.dataForm[this.scriptItem.text][this.scriptItem.dateValue]) {
        case 'second':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number]
          break
        case 'minute':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60
          break
        case 'hour':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60 * 60
          break
        case 'day':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60 * 60 * 24
          break
        case 'week':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60 * 60 * 24 * 7
          break
        case 'month':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60 * 60 * 24 * 30
          break
        case 'year':
          second = this.dataForm[this.scriptItem.text][this.scriptItem.number] * 60 * 60 * 24 * 365
          break

        default:
          second = 1
          break
      }
      return second.toString()
    },
    formatDate (time) {
      return moment(time).format('MM/DD/YYYY HH:mm:ss') + ' ' + moment.tz(time, this.$store.state.user.timezoneId).format('zz')
    },
    formatTime (time) {
      if (time) {
        return moment.tz(time, this.$store.state.user.timezoneId).format('HH:mm:ss') + ' ' + moment.tz(time, this.$store.state.user.timezoneId).format('zz')
      } else {
        return ''
      }
    }
  }
}
</script>
<style lang='scss'>
.scheduleTemplate {
  p {
    margin: 0;
    font-size: 14px;
    font-weight: 400;
    color: #7f7f7f;
    line-height: 20px;
    margin-bottom: 10px;
  }
  .prewive {
    height: 48px;
    background: #e6f7ff;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #138dc7;
    line-height: 20px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    .numRecord {
      display: inline-block;
      text-align: center;
      font-size: 14px;
      font-weight: 600;
      color: #138dc7;
      padding: 0 5px;
    }
    .dateRecord {
      margin-left: 10px;
      display: inline-block;
      text-align: center;
      font-size: 14px;
      font-weight: 600;
      color: #138dc7;
    }
  }
  em::before {
    content: " *";
    color: #e02020;
    padding-right: 12px;
  }
  .el-row {
    .el-col:nth-child(1) {
      width: 18%;
    }
    .el-col:nth-child(2) {
      display: flex;
      width: 80%;
    }
  }
}
.setting {
  color:$--theme-color;
  cursor: pointer;
}
.icon_right {
  margin: 0 14px 0 5px;
}
.custom_time_picker {
  width: 100px!important;
  .el-time-spinner__wrapper:nth-of-type(1) {
    width: 100%;
  }
  .el-time-spinner__wrapper:nth-of-type(2) {
    display: none;
  }
  .time-select-item {
    text-align: center;
  }
}
.cron_popover {
  // padding: 20px;
  .el-popover__title {
    display: none;
  }
}
</style>
<style scoped lang="scss">

#changeContab ::v-deep #tab-0 {
  display: none;
}
.icon_close {
  cursor: pointer;
  &:hover {
    color: $--theme-color;
  }
}
</style>
